/*
 * @Author: zeki mini
 * @Date: 2021-01-04 16:02:58
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-06-17 09:36:55
 * @Description: 更换手机号码
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TextInput,
  Keyboard,
  NativeModules,
  SafeAreaView,
} from 'react-native';
import api from '@/api';
import {
  msg,
  BackImageOn,
  XMHeader,
  SyncStorage,
  Button,
  SendMsgCode,
  cache
} from '@/common';
import { isAndroid, px2dp, fontColorCoffee } from '@/styles';

const { Submit } = Button;

const userApi = api.user;
let CookieManager = NativeModules.RNCookieManagerIOS;
export default class ChangePhone extends Component {
  constructor(props) {
    super(props);
    this.state = {
      code: false,
      begin: 0,
      Msg: '',
      keyShow: true,
      index: 0,
    };
  }

  componentDidMount() {
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () =>
      this.setState({ keyShow: false }),);
    this.xmCountDownButtonPressed();
  }

  render() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { newPhoneNumber } = params;
    return (
      <SafeAreaView>
        <XMHeader
          title='绑定手机号'
          renderLeft={() => {
            return (
              <BackImageOn
                onClick={() => {
                  msg.emit('router: back');
                }}
              />
            );
          }}
        />
        <View style={styles.paddingWrap}>
          <Text style={styles.tit}>输入验证码</Text>
          <View style={styles.tipWrap}>
            <Text style={styles.gray}>已发送4位验证码至：</Text>
            <Text style={styles.mobileColor}>
              {' '}
              {newPhoneNumber}
              {' '}
            </Text>
          </View>
          <View style={styles.flexB}>
            <TextInput
              style={styles.textInputMsg}
              ref='codeInput'
              maxLength={4}
              autoFocus
              caretHidden
              keyboardType='number-pad'
              onSubmitEditing={Keyboard.dismiss}
              blurOnSubmit
              defaultValue={this.state.Msg}
              onChangeText={(text) => {
                this.setState({ Msg: text });
              }}
            />

            {this._getInputItem()}
          </View>
          <View style={styles.marginLeft}>
            <SendMsgCode
              frameStyle={styles.frameStyle}
              activeTextStyle={{ color: fontColorCoffee }}
              count={60}
              pressAction={this.xmCountDownButtonPressed}
              changeWithCount={(count) => `${count}s后重试`}
              id='verification'
              ref={(e) => {
                this.countDownButton = e;
              }}
            />
          </View>

          <Submit
            text='验证'
            disabled={!(this.state.Msg.length === 4)}
            boxStyle={{
              width: px2dp(590),
              height: px2dp(88),
              borderRadius: px2dp(44),
              marginTop: px2dp(72)
            }}
            btnStyle={{}}
            btnTextStyle={{
              fontSize: px2dp(32),
            }}
            onClick={() => {
              this._toPass();
            }}
          />
        </View>
      </SafeAreaView>
    );
  }

  xmCountDownButtonPressed = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { newPhoneNumber } = params;
    this.countDownButton.startCountDown(() => {
      userApi.changePhoneSMSCode({ mobile: newPhoneNumber }).then((res) => {
        if (!res.success) {
          NativeModules.WindowModule.showWindow(
            { content: '验证码发送失败', onlyRightBtn: '1' },
            (e) => {},
          );
          return;
        }
        this.setState({ code: true });
      });
    });
  };

  _toPass = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { newPhoneNumber } = params;
    if (this.state.Msg.length === 4 && this.state.code === true) {
      userApi
        .changePhoneChange({ code: this.state.Msg, mobile: newPhoneNumber })
        .then((res) => {
          if (res.success) {
            userApi.logout().then((resOut) => {
              if (resOut.success) {
                this.setState({ begin: 0, Msg: '', index: 0 });
                // msg.emit('app:tip', { text: '更换成功！请重新登录' })
                msg.emit('app:messageBox', {
                  isVisible: true,
                  text: '更换成功！请重新登录',
                  okText: '确定',
                  isClickBg: false,
                  okFn: () => {
                    SyncStorage.removeItem(cache.USER_INFO);
                    SyncStorage.removeItem(cache.ROLE);
                    if (!isAndroid) {
                      CookieManager.clearAll().then((res) => {
                        console.log('CookieManager.clearAll =>', res);
                      });
                    }
                    msg.emit('router: reset', {
                      routeName: 'LoginView',
                    });
                  },
                });
              } else {
                NativeModules.WindowModule.showWindow(
                  { content: res.msg, onlyRightBtn: '1' },
                  (e) => {},
                );
              }
            });
          } else {
            NativeModules.WindowModule.showWindow(
              { content: res.msg, onlyRightBtn: '1' },
              (e) => {},
            );
          }
        })
        .catch((res) => {
          NativeModules.WindowModule.showWindow(
            { content: res.msg, onlyRightBtn: '1' },
            (e) => {},
          );
        });
    }
  };

  _getInputItem = () => {
    const that = this;
    let inputItem = [];
    let { Msg } = this.state;
    // 理论上TextInput的长度是多少，这个i就小于它
    for (let i = 0; i < 4; i++) {
      inputItem.push(
        // i是从0开始的所以到最后一个框i的值是5
        // 前面的框的右边框设置为0，最后一个边框再将右边框加上
        <TouchableOpacity
          activeOpacity={1}
          key={i}
          style={
            (i === 5
              ? [styles.textInputView, { borderRightWidth: 1 }]
              : [styles.textInputView, { borderRightWidth: 0 }],
            Msg[i]
              ? [styles.textInputView, { borderColor: '#dbdbdb' }]
              : [styles.textInputView, { borderColor: '#f1f0ef' }])
          }
          onPress={() => {
            that.setState({ keyShow: true });
          }}
        >
          {i < Msg.length ? (
            <Text style={{ fontSize: px2dp(48), color: '#333232' }}>
              {Msg[i]}
            </Text>
          ) : null}
        </TouchableOpacity>,
      );
    }
    if (Msg.length === 4) {
      this.refs.codeInput.blur();
    }
    return inputItem;
  };

  UNSAFE_componentWillUnmount() {
    this.setState({ index: 0 });
    this.refs.codeInput.blur();
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    height: '100%',
  },
  active: {
    color: '#BA914A',
    fontSize: px2dp(16),
  },
  disStyle: {
    color: '#999796',
    fontSize: px2dp(16),
  },
  frameStyle: {
    lineHeight: 60,
    backgroundColor: '#fff',
    color: 'red',
    borderWidth: 0,
    fontSize: 18,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  marginLeft: {
    marginLeft: '60%',
  },
  paddingWrap: {
    padding: 30,
    paddingTop: px2dp(60),
  },
  tit: {
    fontSize: px2dp(24 * 2),
    color: '#333232',
    fontWeight: '500',
  },
  tipWrap: {
    flexDirection: 'row',
    marginTop: px2dp(6),
  },
  Text: {
    color: '#999796',
  },
  white: {
    color: '#fff',
  },
  gray: {
    color: '#999796',
    fontSize: px2dp(28),
  },
  mobileColor: {
    color: '#333232',
  },
  btnStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    width: px2dp(320),
    height: 48,
    margin: 'auto',
    borderRadius: 8,
    marginTop: 40,
  },
  focus: {},
  textInputView: {
    height: 85 / 2,
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
    borderBottomWidth: 1,
    borderColor: '#f1f0ef',
    marginRight: 24,
    backgroundColor: '#FFF',
    marginTop: px2dp(40),
  },
  textInputMsg: {
    zIndex: 10,
    position: 'absolute',
    width: '100%',
    height: 100 / 2,
    color: 'transparent',
    backgroundColor: 'transparent',
    top: px2dp(30),
  },
  flexB: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginLeft: px2dp(20),
  },
  confirm: {
    width: '100%',
    textAlign: 'center',
    height: 48,
    lineHeight: 48,
  },
});
